package com.bjc.base.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import lombok.extern.slf4j.Slf4j;

/**
 * 压缩包处理
 *
 * @author 许自辉
 * @date 2017年9月18日
 */
@Slf4j
public class ZIPUtil {

	/**
	 * 删除文件夹及文件
	 */
	public static void delFolder(String folderPath) {
		try {
			// 删除完里面所有内容
			delAllFile(folderPath); 
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete();
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 *  删除指定文件夹下所有文件
	 */
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				// 先删除文件夹里面的文件
				delAllFile(path + "/" + tempList[i]);
				// 再删除空文件夹
				delFolder(path + "/" + tempList[i]);
				flag = true;
			}
		}
		return flag;
	}
	
    /**
     * 压缩文件
     * 
     * @param filePath
     *            待压缩的文件路径
     * @return 压缩后的文件
     * @throws IOException 
     */
    public static File zip(String filePath,String zipName) throws IOException {
        File target = null;
        File source = new File(filePath);
        if (source.exists()) {
            target = new File(source.getParent(), zipName);
            if (target.exists()) {
            	// 删除旧的文件
                target.delete(); 
            }
            FileOutputStream fos = null;
            ZipOutputStream zos = null;
            try {
                fos = new FileOutputStream(target);
                zos = new ZipOutputStream(new BufferedOutputStream(fos));
                // 添加对应的文件Entry
                addEntry("/", source, zos);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
            	zos.close();
            	fos.close();
            }
        }
        return target;
    }
    /**
     * 扫描添加文件Entry
     * 
     * @param base
     *            基路径
     * 
     * @param source
     *            源文件
     * @param zos
     *            Zip文件输出流
     * @throws IOException
     */
    private static void addEntry(String base, File source, ZipOutputStream zos)
            throws IOException {
        // 按目录分级，形如：/aaa/bbb.txt
        String entry = base + source.getName();
        if (source.isDirectory()) {
            for (File file : source.listFiles()) {
                // 递归列出目录下的所有文件，添加文件Entry
                addEntry(entry + "/", file, zos);
            }
        } else {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                byte[] buffer = new byte[1024 * 10];
                fis = new FileInputStream(source);
                bis = new BufferedInputStream(fis, buffer.length);
                int read = 0;
                zos.putNextEntry(new ZipEntry(entry));
                while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, read);
                }
                zos.closeEntry();
            } finally {
                bis.close();
                fis.close();
            }
        }
    }
    
    /**
     * 读本地文件得到byte[]
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] getLocalFileContent(String filename) throws IOException {  
        File f = new File(filename);  
        if (!f.exists()) {  
            throw new FileNotFoundException(filename);  
        }  
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());  
        BufferedInputStream in = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(f));  
            int bufSize = 1024;  
            byte[] buffer = new byte[bufSize];  
            int len = 0;  
            while (-1 != (len = in.read(buffer, 0, bufSize))) {  
                bos.write(buffer, 0, len);  
            }  
            return bos.toByteArray();  
        } catch (IOException e) {  
            throw e;  
        } finally {  
            try {  
                in.close();  
            } catch (IOException e) {  
                throw e;  
            }  
            bos.close();  
        }  
    }
    
    
    /**
     * 读网络文件得到byte[]
     * @param urlName
     * @return
     * @throws IOException
     */
    public static byte[] getNetWorkFileContent(String urlName) throws IOException {  
    	 ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    	//服务器返回的状态 
         int httpResult = 0; 
       //创建URL 
         URL url = new URL(urlName); 
      // 试图连接并取得返回状态码urlconn.connect(); 
         URLConnection urlconn = url.openConnection(); 
         HttpURLConnection httpconn = (HttpURLConnection) urlconn; 
         httpResult = httpconn.getResponseCode(); 
         
         if (httpResult != HttpURLConnection.HTTP_OK){  
             log.info("连接失败！");
         }else { 
//             int filesize = urlconn.getContentLength();  //取数据长度 
             BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream());  
             BufferedOutputStream bos=new BufferedOutputStream(os); 
           //创建存放输入流的缓冲 
             byte[] buffer = new byte[1024]; 
           //读入的字节数 
             int num = -1; 
             while (true) { 
            	// 读入到缓冲区 
                 num = bis.read(buffer); 
                 if (num ==-1){ 
                     bos.flush(); 
                     break; 
                 } 
                 bos.flush(); 
                 bos.write(buffer,0,num); 
             } 
             bos.close(); 
             bis.close(); 
       }
       return os.toByteArray();
    }
    

    
}
